#   This program is free software; you can redistribute it and/or modify
#   it under the terms of the version 3 of the GNU Lesser General Public License
#   as published by the Free Software Foundation.
#
#   This program is distributed in the hope that it will be useful,
#   but WITHOUT ANY WARRANTY; without even the implied warranty of
#   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#   GNU General Public License for more details.
#
#   You should have received a copy of the GNU Lesser General Public License
#   along with this program; if not, write to the Free Software
#   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
# Copyright (c) NEC Deutschland GmbH, NEC HPC Europe
#
# $Id$

import hashlib


__all__ = ["is_integer", "is_integer_type", "is_ip_address",
           "is_primitive_type", "is_simple_sequence",
           "is_simple_map", "md5sum_file", "nested_split"]


def is_integer( value ):
    "Check if parameter can be converted to an integer type (int or long)."
    try:
        int( value )
        return True
    except:
        return False


def is_integer_type( value ):
    "Check if parameter is of type int, long or anything derived."
    return isinstance( value, ( int, long ) )


def is_ip_address( ip ):
    "Check if argument is an IP address (dotted quad)."
    quad = ip.split( "." )
    if len( quad ) != 4:
        return False
    for q in quad:
        try:
            i = int( q )
        except ValueError:
            return False
        if i < 0 or i > 255:
            return False
    return True


def is_primitive_type( value ):
    return isinstance( value, ( bool, int, long, float, str, unicode ) )


def is_simple_sequence( array ):
    result = True
    for element in array:
        if not is_primitive_type( element ):
            result = False
            break
    return result


def is_simple_map( m ):
    result = True
    for element in m.values():
        if not is_primitive_type( element ):
            result = False
            break
    return result


def md5sum_file( fobj ):
    "Returns an md5 hash for a file object"
    m = hashlib.md5()
    while True:
        d = fobj.read(8096)
        if not d:
            break
        m.update(d)
    return m.hexdigest()


def nested_split( string, splitter=" " ):
    "Splits strings and jumps over nestings and quotes."
    quote = [ "'", '"' ]
    nest = { "(": None, ")": "(",
             "[": None, "]": "[",
             "{": None, "}": "{" }
    current_quote = None
    stack = []
    ret = []
    token = ''
    for c in string:
        # in quotes, ignore nestings and other quotations
        if c in quote:
            if current_quote is None:
                current_quote = c
            elif c == current_quote:
                current_quote = None
        if current_quote is None:
            # outside quote
            if c in nest:
                if len( stack ) == 0:
                    if nest[c] is None:
                        stack.append(c)
                else:
                    if nest[c] is None:
                        stack.append(c)
                    elif nest[c] == stack[-1]:
                        stack.pop(-1)
                    else:
                        # nesting error!
                        raise SyntaxWarning, \
                          "Unexpected nesting character '%s' in '%s'" % (c, string)
        if c == splitter and len( stack ) == 0 and current_quote is None:
            ret.append(token)
            token = ''
        else:
            token = token + c
    ret.append(token)
    return ret
